// 导入模块
import WxRequest from 'mina-request'
import Notify from '@vant/weapp/notify/notify'
import Toast from '@vant/weapp/toast/toast';
import { tokenStore } from '../stores/tokenStore'
import { currentUserStore } from '../stores/currentUserStore'

// 对类进行实例化
const instance = new WxRequest({
  baseURL: 'http://localhost:8080',
  timeout: 10800000
})

// 添加请求拦截器
instance.interceptors.request = (config) => {
  let token = tokenStore.token
  if (token) {
    config.header['token'] = token
  }
  return config
}

// 添加响应拦截器
instance.interceptors.response = (response) => {

  // 普通请求处理逻辑
  if (!response.isSuccess) {
    Notify({ type: 'danger', message: '服务异常' })
    return null
  }
  
  if (response.data.code === 401) {
    handleUnauthorized()
    return null
  }
  
  if (response.data.code !== 200) {
    showErrorToast(response.data.message || '出错啦')
    return null
  }

  return response.data
}

// 统一未授权处理
function handleUnauthorized() {
  tokenStore.updateToken('')
  currentUserStore.clearData()
  wx.switchTab({ url: '/pages/user/user' })
}

// 统一错误提示
function showErrorToast(message) {
  Toast.fail(message)
  Toast.setDefaultOptions({ duration: 2000 })
}

// 导出实例
export { instance }